package com.cmcc.qx.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletResponse;

/**
 * HTTP工具类
 * 
 * @author zhangxiaobo
 */
public class HttpUtil {
	private  static  String  encode = "UTF-8";

	public static final String CHARSET = "UTF-8";
	public static final int SC_OK = 200;

	public static void write(OutputStream os, String s) throws IOException {
		try {
			os.write(s.getBytes(CHARSET));
			os.flush();
		} finally {
			os.close();
		}
	}

	public static String read(InputStream is) throws IOException {
		StringBuffer buffer = new StringBuffer();
		try {
			byte[] bs = new byte[1024];
			while (is.read(bs) != -1) {
				buffer.append(new String(bs, CHARSET));
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			is.close();
		}
		return buffer.toString();
	}

	public static void writeObject(OutputStream os, Object obj)
			throws IOException {
		ObjectOutputStream oos = new ObjectOutputStream(os);
		try {
			oos.writeObject(obj);
		} finally {
			oos.close();
			os.close();
		}
	}

	public static Object readObject(InputStream is) throws IOException,
			ClassNotFoundException {
		ObjectInputStream ois = new ObjectInputStream(is);
		try {
			Object obj = ois.readObject();
			return obj;
		} finally {
			ois.close();
			is.close();
		}
	}
	
	/**
	 * 文件上传
	 * @param is
	 * @param file
	 * @throws IOException
	 */
	public static void write(InputStream is, File file) throws IOException {
		FileOutputStream out = null;
		try {
			if (!file.exists())
				file.createNewFile();
			out = new FileOutputStream(file);
			int c;
			byte[] bs = new byte[1024];
			while ((c = is.read(bs)) != -1) {
				for (int i = 0; i < c; i++) {
					out.write(bs[i]);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			is.close();
			out.close();
		}

	}
	
	/**
	 * 文件下载
	 * @param out
	 * @param file
	 * @throws IOException
	 */
	public static void read(OutputStream out, File file) throws IOException {
		FileInputStream is = null;
		try {
			is = new FileInputStream(file);
			if (!file.exists())
				return;
			int c;
			byte[] bs = new byte[1024];
			while ((c = is.read(bs)) != -1) {
				for (int i = 0; i < c; i++) {
					out.write(bs[i]);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			is.close();
			out.close();
		}
	}
	
	public  static  void  print(HttpServletResponse response,String  str) throws IOException{
		response.setContentType("text/html; charset="+encode);
		response.setHeader("Cache-Control", "no-cache");
		PrintWriter out=response.getWriter();
		out.print(str);
		out.close();
	}
}